package com.wtwd.campus.h5_manager.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wtwd.campus.h5_manager.common.Constant;
import com.wtwd.campus.h5_manager.common.PageDataVO;
import com.wtwd.campus.h5_manager.common.RespCode;
import com.wtwd.campus.h5_manager.common.RespEntity;
import com.wtwd.campus.h5_manager.entity.H5Customer;
import com.wtwd.campus.h5_manager.entity.H5ManageRole;
import com.wtwd.campus.h5_manager.entity.H5ManageUser;
import com.wtwd.campus.h5_manager.entity.vo.H5ManageUserVo;
import com.wtwd.campus.h5_manager.service.H5CustomerService;
import com.wtwd.campus.h5_manager.service.H5ManageRoleService;
import com.wtwd.campus.h5_manager.service.H5ManagerUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author mjy
 * @since 2022-03-04
 */
@Api(tags = "账号管理")
@RestController
@RequestMapping("/webH5-manage-user")
public class H5ManageUserController {

    private static final Logger logger = LoggerFactory.getLogger(H5ManageUserController.class);

    @Autowired
    private H5ManagerUserService managerUserService;

    @Autowired
    private H5CustomerService h5CustomerService;

    @Autowired
    private H5ManageRoleService manageRoleService;

    @ApiOperation(value = "分页查询账号数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "currentPage", value = "页数", required = true, dataTypeClass = Integer.class)
            , @ApiImplicitParam(name = "pageSize", value = "页大小", required = true, dataTypeClass = Integer.class)
            , @ApiImplicitParam(name = "name", value = "客户名称", dataType = "String")
    })

    @GetMapping("/queryAccountList")
    public RespEntity<PageDataVO<H5ManageUserVo>> queryAccountList(@RequestParam(defaultValue = "1") Integer currentPage,
                                                                   @RequestParam(defaultValue = "10") Integer pageSize,
                                                                   @RequestParam(value = "name", required = false) String name, HttpServletRequest request) {

        String token = request.getHeader(Constant.H5_MANAGE_TOKEN_KEY);
        Integer userId = managerUserService.getUserIdByToken(token);
        if (userId == null) {
            return new RespEntity<>(RespCode.TOKEN_UNAUTHORIZED);
        }
        logger.info("queryCustomerByConditions currentPage={},pageSize={},name={} userId={}", currentPage, pageSize, name, userId);
        H5ManageUser user = managerUserService.getUserById(userId);
        if (user == null) {
            return new RespEntity<>(RespCode.TOKEN_UNAUTHORIZED);
        }
        Page<H5ManageUser> page = new Page<>(currentPage, pageSize);
        IPage<H5ManageUserVo> userPage = null;
        H5ManageUser userSearch = new H5ManageUser();
        userSearch.setAccount(name);
        if (user.getRoleId().equals(Constant.SYS_MANAGE_USER_ROLE_TYPE_ADMIN)) {//获取所有账号列表
            userSearch.setCustomerId(0);
            userPage = managerUserService.getUserPageByConditions(userSearch, page);
        } else {//只能看到该用户所属客户下的所有账号
            userSearch.setCustomerId(user.getCustomerId());
            userPage = managerUserService.getUserPageByConditions(userSearch, page);
        }
        return RespEntity.success(userPage);
    }

    /**
     * 新增账号
     *
     * @param manageUserVo
     * @return
     */
    @ApiOperation(value = "新增账号")
    @PostMapping("/addAccount")
    public RespEntity addAccount(@RequestBody H5ManageUser manageUserVo) {
        logger.info("addAccount manageUser={}", manageUserVo.toString());
        Boolean authUserName = managerUserService.authUserName(manageUserVo);
        if (!authUserName) {
            return new RespEntity(RespCode.USER_EXIST);
        }
        manageUserVo.setCreateTime(new Date().getTime());
        Integer rest = managerUserService.insertUser(manageUserVo);
        return new RespEntity(rest > 0 ? RespCode.SUCCESS : RespCode.FAILED);
    }

    /**
     * 配合新增加账号下拉框
     * 根据用户动态获取客户(管理员获取所有客户)
     * 客户自己只能获取到自己的客户
     */
    @ApiOperation(value = "下拉框动态获取客户")
    @GetMapping("/queryCustomer")
    public RespEntity<List<H5Customer>> queryCustomer(HttpServletRequest request) {
        String token = request.getHeader(Constant.H5_MANAGE_TOKEN_KEY);
        Integer userId = managerUserService.getUserIdByToken(token);
        if (userId == null) {
            return new RespEntity<>(RespCode.TOKEN_UNAUTHORIZED);
        }
        logger.info("queryCustomer userId={}", userId);
        H5ManageUser user = managerUserService.getUserById(userId);
        if (user == null) {
            return new RespEntity<>(RespCode.TOKEN_UNAUTHORIZED);
        }
        List<H5Customer> customers = h5CustomerService.queryCustomer(user.getCustomerId());
        return new RespEntity<>(RespCode.SUCCESS, customers);
    }

    /**
     * 根据客户id获取客户下的角色(如果用户的身份是管理员角色，则获取总部以及这个客户下的所有角色)
     *
     * @param customerId
     * @return
     */
    @ApiOperation(value = "根据客户Id获取客户下的角色", notes = "通过queryCustomer 获取客户id之后调用此接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "customerId", value = "客户id", required = true, dataTypeClass = Integer.class)
    })
    @GetMapping("/queryRole/{customerId}")
    public RespEntity<List<H5ManageRole>> queryRole(@PathVariable("customerId") Integer customerId, HttpServletRequest request) {
        logger.info("queryRole customerId={}", customerId);
        String token = request.getHeader(Constant.H5_MANAGE_TOKEN_KEY);
        Integer userId = managerUserService.getUserIdByToken(token);
        if (userId == null) {
            return new RespEntity<>(RespCode.TOKEN_UNAUTHORIZED);
        }
        logger.info("queryCustomer userId={}", userId);
        H5ManageUser user = managerUserService.getUserById(userId);
        if (user == null) {
            return new RespEntity<>(RespCode.TOKEN_UNAUTHORIZED);
        }
        List<H5ManageRole> roles = null;
        if (user.getRoleId().equals(Constant.SYS_MANAGE_USER_ROLE_TYPE_ADMIN)) {
            List<Integer> customers = new ArrayList<>();
            customers.add(customerId);
            if (!customerId.equals(user.getCustomerId())) {
                customers.add(user.getCustomerId());
            }
            roles = manageRoleService.queryRoleByCustomerIds(customers);
        } else {
            roles = manageRoleService.queryRoleByCustomerId(customerId);
        }
        return new RespEntity<>(RespCode.SUCCESS, roles);
    }


    /**
     * 修改账号
     *
     * @param manageUserVo
     * @return
     */
    @ApiOperation(value = "修改账号")
    @PutMapping("/updateAccount")
    public RespEntity updateAccount(@RequestBody H5ManageUser manageUserVo) {
        logger.info("updateAccount manageUser={}", manageUserVo.toString());
        if (manageUserVo.getUserId() == null) {
            return new RespEntity(RespCode.NO_PARAM);
        }
        Boolean authUserName = managerUserService.authUserName(manageUserVo);
        if (!authUserName) {
            return new RespEntity(RespCode.USER_EXIST);
        }
        manageUserVo.setUpdateTime(new Date().getTime());
        Integer rest = managerUserService.updateAccount(manageUserVo);
        return new RespEntity(rest > 0 ? RespCode.SUCCESS : RespCode.FAILED);
    }

    /**
     * 删除账号
     */
    @ApiOperation(value = "删除账号")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户Id", required = true, dataTypeClass = Integer.class)
    })
    @DeleteMapping("/deleteAccount/{userId}")
    public RespEntity deleteAccount(@PathVariable("userId") Integer userId) {
        logger.info("deleteAccount userId={}", userId);
        Integer rest = managerUserService.deleteByUserId(userId);
        return new RespEntity(rest > 0 ? RespCode.SUCCESS : RespCode.FAILED);
    }

}

